﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Coldairarrow.Business.Interface.YD_Token;
using static Coldairarrow.Entity.Interface.YDOrdersDTO;

namespace Coldairarrow.Business.Interface
{
    public class YD_YDOrdersInterfaceBusiness : YDInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption YD_Query { get; set; }
        //店铺ID
        public string SellerId { get; set; }
        public YD_YDOrdersInterfaceBusiness()
        {
            this.InterfaceName = "YD订单列表";
            //索引字段
            this.MapFields = GetMapField("YD_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            YD_Query = this.interfaceOption.Where(x => x.OperateType == "YD_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, YD_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, YD_QueryEventArgs queryEventArgs)
        {
            try
            {
                queryEventArgs.HttpClient.ContentType = "GET";
                //设置请求头参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var parList = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='Yandex'");
                queryEventArgs.TokeList = new List<YD_Token>();
                //将所有店铺ID转换成对象，便于后续批量更换店铺同步数据
                foreach (var item1 in parList.Where(x => x.Type == "Api-Key"))
                {

                    //店铺的ApiKey
                    var ApiKey = item1.Value;
                    var clist = parList.Where(x => x.Notes == item1.Name);
                    foreach (var item2 in clist)
                    {
                        //FBS/FBY的ID
                        YD_Token t = new YD_Token();
                        t.ApiKey = ApiKey;
                        t.CampaignsId = item2.Value;
                        t.Id = t.ApiKey + t.CampaignsId;
                        t.Campaign = item2.Name;
                        t.SellerId = item2.Describe;
                        queryEventArgs.TokeList.Add(t);
                    }

                }
                queryEventArgs.Page.PageSize = YD_Query.ExcInterval;
                queryEventArgs.CustomData = queryEventArgs.HttpClient.Url;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, YD_QueryEventArgs queryEventArgs)
        {
            var apiKeys = queryEventArgs.TokeList.Where(x => x.Flag.IsNullOrEmpty());
            if (!apiKeys.IsNullOrEmpty())
            {

                //获取请求的数据
                YD_ReqDTO data = new YD_ReqDTO();
                data.fromDate = DateTime.Now.AddDays(-queryEventArgs.Page.PageSize).ToString("yyyy-MM-dd");
                data.toDate = DateTime.Now.ToString("yyyy-MM-dd");
                //data.fromDate = "2025-03-01";
                //data.toDate = "2025-03-31";
                data.page_token = queryEventArgs.Page.SidIndex_s;
                //设置请求URL信息
                var apiKey = apiKeys.First();
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Api-Key", apiKey.ApiKey);
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                queryEventArgs.HttpClient.Url = queryEventArgs.CustomData + $"?fromDate={data.fromDate}&toDate={data.toDate}&page_token={data.page_token}";
                queryEventArgs.HttpClient.Url = queryEventArgs.HttpClient.Url.Replace("{campaignId}", apiKey.CampaignsId);//替换ID
                //记录ID
                queryEventArgs.Page.Temp3 = apiKey.Id;
                //queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, YD_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                YDOrdersDTO result = (YDOrdersDTO)JsonConvert.DeserializeObject<YDOrdersDTO>(queryEventArgs.ResultStr);
                if (!result.paging.IsNullOrEmpty() && !result.paging.nextPageToken.IsNullOrEmpty())
                {
                    queryEventArgs.Page.SidIndex_s = result.paging.nextPageToken;
                }
                else
                {
                    queryEventArgs.Page.SidIndex_s = "";
                    queryEventArgs.TokeList.Where(x => x.Id == queryEventArgs.Page.Temp3).First().Flag = "Y";
                    //判断所有店铺循环都执行完成
                    if (queryEventArgs.TokeList.Where(x => x.Flag.IsNullOrEmpty()).IsNullOrEmpty()) queryEventArgs.Page.Complete = true;
                }
                queryEventArgs.Success = true;
                //设置店铺及id信息
                var f = queryEventArgs.TokeList.Where(x => x.Id == queryEventArgs.Page.Temp3).First();
                foreach (var item1 in result.orders)
                {
                    item1.SellerId = f.SellerId;
                    item1.ShipmentType = f.Campaign;
                }
                queryEventArgs.Rows = result.orders;
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            //获取报表代码
            List<YDReturnsDTO.Returns> code = await this.QueryAsync<YDReturnsDTO.Returns>(this.YD_Query, SqlDb);

        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
